//
//  FJHomeViewController.swift
//  FruitJuice
//
//  Created by Rae on 2023/12/15.
//

import UIKit
import JXBanner
import JXPageControl

class FJHomeViewController: FJBaseViewController {

    private let backView            = c_make_ex(UIImageView.self)
        .mode(.scaleAspectFill).image("FJ_Profile_bg").end()
    private var topView = FJHomeTopView()
    private let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    var dataSource:[InfoUtil.room] = []
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        topView.updateUserInfo()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        loadData()
        navigation.bar.isHidden = true
        
        view.subviews{
            backView.subviews{
                topView
                collectionView
            }
        }
        
        backView.fillContainer()
        topView.leading(0).trailing(0).top(0).height(.statusHeight + 215.0)
        collectionView.leading(0).trailing(0).height(465)
        collectionView.Top == topView.Bottom
        
        backView.isUserInteractionEnabled = true
        let itemW = .screenWidth-30.0
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 30
        layout.minimumInteritemSpacing = 30
        layout.itemSize = CGSize(width: itemW, height: 465)
        layout.sectionInset = UIEdgeInsets(top: 0, left: 15.0, bottom: 0, right: 15.0)
        layout.scrollDirection = .horizontal
        collectionView.style { v in
            v.collectionViewLayout = layout
            v.backgroundColor = .clear
            v.isPagingEnabled = true
            v.register(FJHomeItem.self, forCellWithReuseIdentifier: FJHomeItem.description())
            v.showsHorizontalScrollIndicator = false
            v.delegate = self
            v.dataSource = self
        }
        
        topView.pushToProfileVCClosure = {
            self.navigationController?.pushViewController(FJProfileViewController(), animated: true)
        }
        topView.pushToMsgVCClosure = {
            self.navigationController?.pushViewController(FJMessageViewController(), animated: true)
        }
        topView.pushToRecordVCClosure = {
            self.navigationController?.pushViewController(FJRecordViewController(), animated: true)
        }
        topView.pushToPopularVCClosure = {
            self.navigationController?.pushViewController(FJPopularViewController(), animated: true)
        }
        
        NotificationCenter.default.addObserver(self, selector: #selector(toPushVC), name: .toPushVC, object: nil)
    }
    
    private func loadData(){
        
        RT.getRoomList { list in
            self.dataSource.removeAll()
            for item in list{
                if item?.houseName == "___*FruitJuice" {
                    self.dataSource.append(item!)
                }
            }
            self.collectionView.reloadData()
        }
    }

    @objc private func toPushVC(){
        
        self.navigationController?.pushViewController(FJPushViewController(), animated: true)
    }
}

extension FJHomeViewController: UICollectionViewDelegate,UICollectionViewDataSource{
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataSource.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let item = collectionView.dequeueReusableCell(withReuseIdentifier: FJHomeItem.description(), for: indexPath) as? FJHomeItem else { return UICollectionViewCell() }
        item.model = dataSource[indexPath.row]
        return item
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        let detailVC = FJDetailViewController()
        detailVC.model = dataSource[indexPath.row]
        self.navigationController?.pushViewController(detailVC, animated: true)
    }
}


class FJHomeItem: UICollectionViewCell {
    
    private let backView = c_make_ex(UIView.self)
        .bgColor(.white).corner(23).end()
    private let iconImageView = c_make_ex(UIImageView.self)
        .mode(.scaleAspectFill).corner(8).end()
    private let bottomView = c_make_ex(UIImageView.self)
        .image("FJ_Home_bottomView").end()
    private let titleLabel = c_make_ex(UILabel.self)
        .color(.black).font(18.font_regular).line(2)
        .text("Peel and cut oranges into juicer, addadda add  appropriate amount of tomatoesclick…").end()
    private let pushButton = c_make_ex(UIButton.self)
        .image("FJ_Home_push").end()
    private let scoreLabel = c_make_ex(UILabel.self)
        .color("#FF9133").font(18.font_regular).text("4.5").end()
    private let priceLabel = UIIconButton(style: .leading(itemSpace: 4))
    
    private lazy var linearBanner: JXBanner = {[weak self] in
        let banner = JXBanner()
        banner.placeholderImgView.image = UIImage(named: "FJ_Common_placeholder")
        banner.indentify = "linearBanner"
        banner.delegate = self
        banner.dataSource = self
        banner.isUserInteractionEnabled = false
        return banner
    }()
    
    private var onebutton: UIButton = {
        let button = UIButton(type: .custom)
        button.setImage("FJ_Home_score".toImage, for: .normal)
        button.setImage("FJ_Home_score_sel".toImage, for: .selected)
        return button
    }()
    private var twobutton: UIButton = {
        let button = UIButton(type: .custom)
        button.setImage("FJ_Home_score".toImage, for: .normal)
        button.setImage("FJ_Home_score_sel".toImage, for: .selected)
        return button
     }()
    private var threebutton: UIButton = {
        let button = UIButton(type: .custom)
        button.setImage("FJ_Home_score".toImage, for: .normal)
        button.setImage("FJ_Home_score_sel".toImage, for: .selected)
        return button
     }()
    private var fourbutton: UIButton = {
        let button = UIButton(type: .custom)
        button.setImage("FJ_Home_score".toImage, for: .normal)
        button.setImage("FJ_Home_score_sel".toImage, for: .selected)
        return button
     }()
    private var fivebutton: UIButton = {
        let button = UIButton(type: .custom)
        button.setImage("FJ_Home_score".toImage, for: .normal)
        button.setImage("FJ_Home_score_sel".toImage, for: .selected)
        return button
     }()
    
    var model:InfoUtil.room?{
        didSet{
            guard let md = model else {
                return
            }
            
            if let price = md.price, price.count > 0 {
                priceLabel.isHidden = false
                priceLabel.setTitle(md.price, for: .normal)
            }else{
                priceLabel.isHidden = true
            }
            titleLabel.text = md.descInfo
            if let headImg = md.info3 {
                iconImageView.loadImage(url: headImg,placehold: "FJ_Common_avator")
            }else{
                iconImageView.image = "FJ_Common_avator".toImage
            }
            let array = md.icon!.components(separatedBy: ",")
            imgDataArr = array
            linearBanner.reloadView()
        }
    }
    private var imgDataArr = [String]()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.backgroundColor = .white
        
        contentView.subviews {
            backView.subviews{
                linearBanner.subviews{
                    iconImageView
                }
                bottomView.subviews{
                    titleLabel
                    onebutton
                    twobutton
                    threebutton
                    fourbutton
                    fivebutton
                    scoreLabel
                }
                pushButton
                priceLabel
            }
        }

        backView.fillContainer()
        linearBanner.leading(0).trailing(0).top(0).height(345)
        iconImageView.trailing(17.5).top(12.5).size(40)
        bottomView.leading(0).trailing(0).bottom(0).top(310)
        titleLabel.leading(15).trailing(15).top(54)
        pushButton.trailing(0).top(300).size(60)
        onebutton.leading(18).bottom(15.5).width(20).height(19)
        twobutton.leading(46).bottom(15.5).width(20).height(19)
        threebutton.leading(74).bottom(15.5).width(20).height(19)
        fourbutton.leading(102).bottom(15.5).width(20).height(19)
        fivebutton.leading(130).bottom(15.5).width(20).height(19)
        scoreLabel.leading(161)
        scoreLabel.CenterY == fivebutton.CenterY
        priceLabel.leading(0).top(0).width(90).height(40)
        
        priceLabel.style { v in
            v.iconSize = CGSize(width: 33, height: 33)
            v.setTitleColor(.white, for: .normal)
            v.setTitle("20", for: .normal)
            v.setImage("FJ_Profile_Coins_coin".toImage, for: .normal)
            v.titleLabel?.font = 19.font_medium
            v.backgroundColor = "#A2C971".toColor
            v.isUserInteractionEnabled = false
            v.contentHorizontalAlignment = .center
            v.layer.cornerRadius = 17
            v.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMaxYCorner]
        }
        pushButton.addTarget(self, action: #selector(clickPushButton), for: .touchUpInside)
    }
    
    @objc private func clickPushButton(){
        NotificationCenter.default.post(name: .toPushVC, object: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

extension FJHomeItem: JXBannerDataSource, JXBannerDelegate {

    func jxBanner(numberOfItems banner: JXBannerType) -> Int {
        return imgDataArr.count
    }

    func jxBanner(_ banner: JXBannerType) -> (JXBannerCellRegister) {

        return JXBannerCellRegister(type: FJBannerCell.self,
                                        reuseIdentifier: "FJBannerCell")
    }

    func jxBanner(_ banner: JXBannerType,
                  cellForItemAt index: Int,
                  cell: UICollectionViewCell) -> UICollectionViewCell {

        guard let imageCell = cell as? FJBannerCell else {
            return cell
        }
        imageCell.imgUrl = imgDataArr[index]
        return imageCell
    }

    func jxBanner(_ banner: JXBannerType,
                  params: JXBannerParams) -> JXBannerParams {

        return params
            .timeInterval(2)
            .cycleWay(.forward)
            .isAutoPlay(false)
    }

    func jxBanner(pageControl banner: JXBannerType,
                  numberOfPages: Int,
                  coverView: UIView,
                  builder: JXBannerPageControlBuilder) -> JXBannerPageControlBuilder {

        let pageControl = JXPageControlScale()
        pageControl.contentMode = .bottom
        pageControl.activeSize = CGSize(width: 15, height: 6)
        pageControl.inactiveSize = CGSize(width: 6, height: 6)
        pageControl.activeColor = .white
        pageControl.inactiveColor = .white.alpha(0.4)
        pageControl.columnSpacing = 0
        pageControl.isAnimation = true
        builder.pageControl = pageControl
        builder.layout = {
            pageControl.snp.makeConstraints { (maker) in
                maker.centerX.equalTo(coverView)
                maker.bottom.equalTo(coverView.snp.bottom).offset(-20)
                maker.height.equalTo(20)
            }
        }
        return builder

    }
}
